package com.vtest.quartz.service.impl;

import com.vtest.quartz.domain.job.SysJob;
import com.vtest.quartz.mapper.SysJobMapper;
import com.vtest.quartz.service.SysJobService;
import com.vtest.quartz.utils.constants.ScheduleConstants;
import com.vtest.quartz.utils.quartz.ScheduleUtils;
import com.vtest.quartz.utils.exception.TaskException;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @program: Quartz
 * @author: tiger
 * @create: 2024-12-12 14:09
 * @Description :定时任务调度信息 服务层
 */

@Service
@Slf4j
public class SysJobServiceImpl implements SysJobService {

    @Autowired
    private Scheduler scheduler;


    @Autowired
    private SysJobMapper jobMapper;

    /**
     * 项目启动时，初始化定时器 主要是防止手动修改数据库导致未同步到定时任务处理（注：不能手动修改数据库ID和任务组名，否则会导致脏数据）
     */
    @PostConstruct
    public void init() throws SchedulerException, TaskException {
        scheduler.clear();
        System.out.println("init------");
        List<SysJob> jobList = jobMapper.selectJobAll();
        for (SysJob job : jobList) {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
    }

    /**
     * 获取quartz调度器的计划任务列表
     */
    @Override
    public List<SysJob> selectJobList()
    {
        return jobMapper.selectJobAll();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertJob(SysJob job) throws SchedulerException, TaskException {
        job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        int rows = jobMapper.insertJob(job);
        if (rows > 0)
        {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
        return rows;
    }
}
